
//
//  SearchVC.m
//  DataStatistics
//
//  Created by Kang on 15/10/13.
//  Copyright © 2015年 YTYangK. All rights reserved.
//


#import "SearchVC.h"
#import "EquipmenCell.h"
#import "SearchViewModel.h" //搜索ViewModel
#import "JournalModel.h"
#import "EquipmenModel.h"
#import <CoreData/CoreData.h> // 暂时未使用，打算在后期版本使用
#import "SystemInfoController.h"// 扫描获取到的设备详情
#import "HeadSearchViewAssembly.h"
#import "UIView+RGSize.h"
#import "GetiPhoneDevice.h"
#import "JPUSH.h"
#import "JournalListController.h"
#import "WelcomeViewController.h"
#import "DetailspageViewController.h"

#define  RECORD_INDEX_PATH   @"recordIndexPath"

@interface SearchVC () <UIPopoverPresentationControllerDelegate, EquipmenCellDelegate,SystemInfoControllerDelegate,NSObject,HeadSearchViewAssemblyDelegete,YLZHoledViewDelegate,UIScrollViewDelegate> {

    // 需要其他控件控制刷新
    MJRefreshNormalHeader* header;
    MJRefreshBackNormalFooter* footer;

    // 请求字典
    NSDictionary* parameterDic;
    // 点击状态 ， yse -点击 ， no - 没有
    BOOL isDetermineClick;
    //保存数 历史数量
    NSString * recordChoiceDevice;
    //保存选择的设备ID
    NSInteger  recordChoiceDeviceInt;
    // 传给日志列表的未读数量
    int recordChoiceUnread;
    // 搜索字符串值
    NSString * searchTextVlue;
    // 搜索头部 Nav
    HeadSearchViewAssembly *titleView;
    // 教程是否可以全局点击  YES = 是， NO = 不是；
    BOOL isMaskLayerGlobalClick;
    
    UIView *MaskView;//添加遮罩挡住其他手势;
    UIButton *_maskButton;
    
    int a;//小红点变量
    int b;//请求变量
    int state;//请求排序变量
    UIScrollView *ScrollView;//引导
    BOOL delete;
}

/** 第三方封装方法 */
//@property (strong, nonatomic) DeploySDK *deploySDK;
/** 透明覆盖背景 */
@property (strong, nonatomic) UIView* maskView;
/** 接收本地语言标识 */
@property (strong, nonatomic) NSString *localStr;
/** 没显示数据时的图片 */
@property (strong, nonatomic) UIButton *notDataBtn;
/** 列表页数 */
@property (assign, nonatomic) int                        page;
/**  判断列表状态 （YES - 刷新状态， NO - 加载状态） */
@property (assign, nonatomic) BOOL                       isToSearchUpdate;
/** 判断数据是否加载完成 */
//@property (assign, nonatomic) BOOL   isLo

// cell
@property (strong, nonatomic) EquipmenCell *cell;

@property (strong,nonatomic)NSArray *hollowFrames;

@end

@implementation SearchVC
singleton_for_implementation(SearchVC)


static NSString *cellIdentifier = @"EquipmenCell";

#pragma mark - 原生代码
- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadCount) name:MDC_SET_BADGE object:nil]; // 激活时，推送时
    [[UIApplication sharedApplication] addObserver:self forKeyPath:@"applicationIconBadgeNumber" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"监控属性值变化"];
    
    
    [self hsUpdateApp];
    state = 0;
    
    
    
    
}

- (IBAction)devicebtnStateViewCallBakc:(UIButton *)sender {
    
    if (sender.tag ==88) {
        [self.ALLBtn setBackgroundImage:[UIImage imageNamed:@"menu-l-on"] forState:UIControlStateNormal];
        [self.FaultBtn setBackgroundImage:[UIImage imageNamed:@"menu-c-off"] forState:UIControlStateNormal];
        [self.LatelyBtn setBackgroundImage:[UIImage imageNamed:@"menu-r-off"] forState:UIControlStateNormal];
        state = 0;
        
        
    }else if (sender.tag == 89){
        
        [self.ALLBtn setBackgroundImage:[UIImage imageNamed:@"menu-l-off"] forState:UIControlStateNormal];
        [self.FaultBtn setBackgroundImage:[UIImage imageNamed:@"menu-c-on"] forState:UIControlStateNormal];
        [self.LatelyBtn setBackgroundImage:[UIImage imageNamed:@"menu-r-off"] forState:UIControlStateNormal];
        state = 1;
        
    }else if (sender.tag == 90){
        [self.ALLBtn setBackgroundImage:[UIImage imageNamed:@"menu-l-off"] forState:UIControlStateNormal];
        [self.FaultBtn setBackgroundImage:[UIImage imageNamed:@"menu-c-off"] forState:UIControlStateNormal];
        [self.LatelyBtn setBackgroundImage:[UIImage imageNamed:@"menu-r-on"] forState:UIControlStateNormal];
        state = 2;
        
    }

    [header beginRefreshing];

    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

//    [Cview removeFromSuperview];
    
    
    
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     
    [[JPUSH sharedJPUSH] albbBindChannel];


    
    
    if ([NSUD objectForKey:@"QR"] ==nil) {
        //开启教程
        [self addCourseListOfDimensionalCodeScanning];
        
    }else if ([[NSUD objectForKey:@"QR"]isEqualToString:@"NO"]){
        //移除教程
        [self removeMaskLayer];
        [MaskView removeFromSuperview];
    }
  

}




#pragma mark - Table view UI and Data
- (void)updateUI {
    _isSearchJumpLiet     =NO;
     isDetermineClick       =   NO;      //状态标识 -是否点击了某行？
    _isToSearchUpdate     =   YES;
    self.clickFinished        =   YES;
    self.page = 0;
    searchTextVlue = @"";
    
    self.searchTableView.backgroundColor = RGB(33, 38, 44, 1);
    self.searchTableView.tableFooterView=   [[UIView alloc]init];//隐藏多余的分割线
    [self.searchTableView addSubview:self.notDataBtn];
    //初始化MJ刷新加载组件
    [self initTableViewMJRefresh];
    // 搜索头部
    [self setupMiddleNavigationItem];
    
}



- (void)setupMiddleNavigationItem {
    /**  初始化 Nav UI */
    titleView = [[HeadSearchViewAssembly alloc] initWithViewController:self];
    titleView.delegete = self;
     UIBarButtonItem *btn   = [titleView rithtScanBtn];
    self.navigationItem.titleView = titleView;
    self.navigationItem.rightBarButtonItem = btn;
}


- (void)initTableViewMJRefresh {
    /**x
     *  上下拉刷新控件初始化
     */
    header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isToSearchUpdate = YES;
        self.page = 0;
        [self requestURLwithViewForpage:self.page];
        a=0;

    }];
    
    header.automaticallyChangeAlpha = NO;
    header.lastUpdatedTimeLabel.hidden = NO;
    self.searchTableView.header = header;
    [header beginRefreshing];
    footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.isToSearchUpdate = NO;
        b=self.page+19;
        b++;
        self.page = b;
        [self requestURLwithViewForpage:b];
    }];
    self.searchTableView.footer = footer;
}


- (void)requestURLwithViewForpage:(int)page {
    /**
      * 请求方法
      */
    NSString * str  =  ([searchTextVlue rangeOfString:@"搜索"].location != NSNotFound) ? @"" : searchTextVlue ;
    
    NSNumber* num = [NSNumber numberWithInt:page];
    
    parameterDic = @{ @"iDisplayStart" : num,
                      @"iDisplayLength" : @"20",@"token":[NSUD objectForKey:@"token"],@"deviceName":str,@"sortState":@(state)};
    
    NSLog(@"设备列表 ==== %@",parameterDic);
    
    [SearchViewModel requestWithUrlForSearchIn:self andParam:parameterDic success:^(NSMutableArray *model) {
        [header endRefreshing];
        [footer endRefreshing];
 
//        NSLog(@"小红点 === %@",model);
        for (NSDictionary *dic in model) {
            NSString *unread =dic[@"unread"];
            
            a = [unread intValue]+a;
            
            [SearchViewModel sharedSearchViewModel].unreadCount =[NSString stringWithFormat:@"%d",a];
            self.navigationController.tabBarItem.badgeValue = [SearchViewModel sharedSearchViewModel].unreadCount;
            [UIApplication sharedApplication].applicationIconBadgeNumber = [SearchViewModel sharedSearchViewModel].unreadCount.intValue;
        }
        
        NSMutableArray *scheduingAry = [EListModel mj_objectArrayWithKeyValuesArray:model];
        
        if (self.isToSearchUpdate) { // 更新
            self.notDataBtn.hidden = YES;

            if (model ==nil) {
                
                [self.searchModelAry removeAllObjects];
                [self.searchTableView reloadData];
                 self.notDataBtn.hidden = NO;
            }else{
                [self.searchModelAry removeAllObjects];
                for (NSDictionary *dic in scheduingAry) {
                    [self.searchModelAry addObject:dic];
                 }
                
                [self.searchTableView reloadData];

            }
            self.clickFinished  = true;

        }else { // 加载
            if (model ==nil) {
                [footer endRefreshing];
            }else {
                for (NSDictionary *dic in scheduingAry) {
                    [self.searchModelAry addObject:dic];
                }
                [self.searchTableView reloadData];
            }
     }


        
    } failure:^(NSString *error) {
      
        if (self.searchModelAry.count ==0) {
            self.notDataBtn.hidden = NO;
            
        }
        
        [self.searchTableView.header endRefreshing];
        [self.searchTableView.footer endRefreshing];
        if(![error isEqualToString:@"数据错误"]) {
             [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:self.view];
        }
    }];
    
}

#pragma mark - YLZHoledView Delegate
- (void)holedView:(YLZHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index {
    if (index == 0) {
        if (holedView.tag == 120) {
            [self.holdedView removeFromSuperview];
            [titleView showQRCode:nil];
        }else if(holedView.tag == 121) {
        }else if (holedView.tag == 122) {

        }else if (holedView.tag == 123){
            [self removeMaskLayer];
            self.navigationController.tabBarController.selectedIndex = 1;
        }
    }
    
    
    if (isMaskLayerGlobalClick) {
        isMaskLayerGlobalClick = NO;
    }
}


#pragma mark - TableView Delegate
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return 85;
}

//点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    isDetermineClick = YES;
    if (isDetermineClick == YES) {
        NSLog(@"数据 ======= %@",self.searchModelAry);
        EListModel* list = self.searchModelAry[indexPath.row];
        recordChoiceDevice = list.device_id;
        recordChoiceDeviceInt = indexPath.row;
        recordChoiceUnread = list.unread;
        
        [self subtractUnreadCount:list.unread];
        [list setValue:@0 forKey:@"unread"];
        [NSUD setObject:list.nickname forKey:MDC_NICK_NMAE];
        
        // 数组 替换的下标  ， 替换赋予的内容
        [self.searchModelAry replaceObjectAtIndex:indexPath.row withObject:list];
        
        // 更新 cell
        NSIndexPath* indexPaths = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        [self.searchTableView reloadRowsAtIndexPaths:@[ indexPaths ] withRowAnimation:UITableViewRowAnimationNone];
        isDetermineClick = NO;
        
        UIBarButtonItem * item = [[UIBarButtonItem alloc] init];
        item.title = NSLocalizedString(@"back", nil);
        self.navigationItem.backBarButtonItem = item;
        
//        [SearchViewModel jumpListDetailWithListModel:_searchModelAry[indexPath.row] forViewController:self];
        [self performSegueWithIdentifier:@"jumpJournalList"  sender:self];
        //获取当前设备名
        [NSUD setObject:list.name forKey:@"device_name"];
        [NSUD setObject:list.imie forKey:@"id"];
    }
}


#pragma mark -  TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger row = self.searchModelAry.count;
    return row;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    self.cell = [EquipmenCell initCellWithCellView:tableView reuseIdentifier:cellIdentifier];
    self.cell.delegate = self;
    self.cell.modelCellData =  self.searchModelAry[indexPath.row];
    
    [self.cell judgeBtnVlue:self.cell.modelCellData.unread isDetermineClick:isDetermineClick];
    
    return self.cell;
}




//取消删除模块

// 这里可以指定那一条是否可以编辑
- (BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath {
    delete = NO;

    return YES;
}
 
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    delete = YES;
    
    return UITableViewCellEditingStyleDelete;
}

 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
      if (editingStyle == UITableViewCellEditingStyleDelete) {
                    //数据请求

         NSDictionary* dic = @{ @"imie" : [self.searchModelAry[indexPath.row] imie], @"token":[NSUD objectForKey:@"token"]};
          
          [SearchViewModel requestWithUrlForDeviceRemoveBinding:self andParam:dic success:^(RemoveBindingModel *model) {
                        // 清nil
                        if (_searchModelAry.count <= 1) {
                            self.navigationController.tabBarItem.badgeValue = nil;
                        }
                        EListModel * lis = _searchModelAry[indexPath.row];
                       // 获取推送总数
                        NSString* status =  [NSString stringWithFormat:@"%ld", (long)[UIApplication sharedApplication].applicationIconBadgeNumber];                         int  i = status.intValue - lis.unread;
                        [UIApplication sharedApplication].applicationIconBadgeNumber = i;
                       //删除数据源   _searchModelAry.mutableCopy，如果_searchModelAry,是可变的 再来用mutableCopy 会导致数据无法删除
                        [_searchModelAry removeObjectAtIndex:indexPath.row];
                        [self.searchTableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationLeft]; //删除自己tavleView 的数据
                        [header beginRefreshing];
                        
                    } failure:^(NSString *error) {
                        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:self.view];
                    }];
            }
}


- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {  //滑动时修改文字
    return @"删除";
}



#pragma  mark - HeardSearch Delegate
//FIXME: 这里需要重新考虑
- (void)headSearchDeviceForKeyWord:(UITextField *)textView {
    /**
     *  头部搜索
     */
    searchTextVlue = textView.text;
    [header beginRefreshing];
}


#pragma mark - SystemInfoController Delegate
- (void)dismissViewControllerWithDeviceVlue:(NSString *)Str {
     /** 二维码扫描详情页面设备代理 */
    

    [header beginRefreshing];

   if ([[NSUD objectForKey:@"QR"]isEqualToString:@"NO"]){
        //移除教程
        [self removeMaskLayer];
        [MaskView removeFromSuperview];
    }else{
        //引导
        [self AddDeviceListBoot];
    }
    
}




#define mark - Other
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    /**
     * 监控数值变化 - 监控对象是 applicationIconBadgeNumber
     */
    NSInteger integer  = [UIApplication sharedApplication].applicationIconBadgeNumber;
    NSLog(@"----->%ld",(long)integer);
    if ([keyPath isEqualToString:@"applicationIconBadgeNumber"]) {
        if (integer <=0) {
            self.navigationController.tabBarItem.badgeValue = nil;
        }else {
            //???: 崩溃了~o(≧口≦)o
            self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",(long)integer];
        }
    }
    NSLog(@"%@---->%@---->%@--->%@",keyPath,object,change,context);
}

- (void)setupUnreadCount {
    /**
     *  全局更新的内容
     */
    NSString *str = [SearchViewModel sharedSearchViewModel].unreadCount;
    if (str.intValue<= 0 ) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    
    [header beginRefreshing]; // 刷新列表
}



- (void)subtractUnreadCount:(int)count {
    /**
     *  清除未读信息 - 计数
     */
    int resultCount = 0;
    int numberBadge = [[NSUD objectForKey:@"applicationIconBadgeNumber"] intValue];   // icon 总数
    int tabBadgeValue  = [self.navigationController.tabBarItem.badgeValue intValue];       // tabBadge 总数
    int ecvm_unreadCount = [[SearchViewModel sharedSearchViewModel].unreadCount intValue]; // 后台总数
    
//TODO: 如果icon 数量异常
    // 被减数 是否为 0 或者小于零
    if (count > 0) {
        // 判断tab 有数量不
        if (tabBadgeValue >= 0) {
            if (numberBadge >= 0) {
                resultCount = tabBadgeValue - count;
            }else {
                resultCount = 0;
            }
        }
        
        // 判断计算的变量 coun 值
        if (resultCount <= 0) {
            self.navigationController.tabBarItem.badgeValue = nil;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        }
        else {
            self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", resultCount];
            [UIApplication sharedApplication].applicationIconBadgeNumber = resultCount;
            [NSUD setObject:@(resultCount) forKey:@"applicationIconBadgeNumber"];
        }
        
        [SearchViewModel sharedSearchViewModel].unreadCount = [NSString stringWithFormat:@"%d", resultCount];
    }
    else {
        
        if (ecvm_unreadCount> 0) {
            [UIApplication sharedApplication].applicationIconBadgeNumber = ecvm_unreadCount;
            [NSUD setObject:@(ecvm_unreadCount) forKey:@"applicationIconBadgeNumber"];
        }else {
            //  小于等于0
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            [NSUD setObject:@(0) forKey:@"applicationIconBadgeNumber"];
        }
    }
}


- (void)addUnreadCount:(id)vlue {
    /**
     *  前台通知来时计算未读信息
     */
    NSDictionary  *dic = (NSDictionary *)vlue;
    NSString *deviceCodeStr = [vlue  objectForKey:@"imie"];
    
    int inde = 0;
    for (EListModel* obj in _searchModelAry) {
        NSLog(@"%d - - ->%@",inde,obj.device_id);
        if ([deviceCodeStr isEqualToString:obj.device_id]) {
            EListModel* list = self.searchModelAry[inde];
            NSString *status = [dic objectForKey:@"unread"];
            [list setValue:[NSNumber numberWithInt:status.intValue] forKey:@"unread"];
            NSIndexPath *indexPat =  [NSIndexPath indexPathForRow:inde inSection:0];
            [self.searchTableView reloadRowsAtIndexPaths:@[ indexPat ] withRowAnimation:UITableViewRowAnimationNone];
            break;
        }
        inde++;
    }
    
}

- (void)JumpWithVlue:(id)vlue {
    /**
     *  根据数据 - 跳转页面
     */
    NSDictionary  *dic = vlue;
    NSLog(@"%@",dic);
    
    int inde = 0;
    for (EListModel* obj in self.searchModelAry) {
        NSLog(@"%d - - ->%@",inde,obj.imie);
        if ([[vlue objectForKey:@"imie"] isEqualToString:obj.imie]) {
            EListModel* list = self.searchModelAry[inde];
            recordChoiceDevice = list.device_id;   // 后台- 单条数
            recordChoiceDeviceInt = inde;
            recordChoiceUnread = list.unread;
            [self subtractUnreadCount:list.unread];
            [list setValue:@0 forKey:@"unread"];
            [NSUD setObject:list.nickname forKey:MDC_NICK_NMAE];//objectForKey:
            NSIndexPath *indexPat =  [NSIndexPath indexPathForRow:inde inSection:0];
            [self.searchTableView reloadRowsAtIndexPaths:@[ indexPat ] withRowAnimation:UITableViewRowAnimationNone];
          //  [SearchViewModel jumpListDetailWithListModel:_searchModelAry[inde] forViewController:self];
            [self performSegueWithIdentifier:@"jumpJournalList"  sender:self];
            //获取当前设备名
            [NSUD setObject:list.imie forKey:@"id"];
                        
            break;
        }
        inde++;
    }
}


/**
 *  移除新手教程并且设置 nil
 */
- (void)removeMaskLayer {
    // 移除并且设置 nil
    [self.holdedView removeFromSuperview];
    self.holdedView = nil;
}

/**
 *  教程-二维码扫描引导
 */
- (void)addCourseListOfDimensionalCodeScanning {
    
    CGFloat pointFloat;
    CGFloat pointFloat1;

    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        pointFloat = 45.5;
        pointFloat1=22;
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        pointFloat = 46.5;
        pointFloat1=22;
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
        pointFloat = 49.5;
        pointFloat1=22;
    }else {
        pointFloat = 45;
        pointFloat1=45;
    }
    
    
    UIImageView *sketchMapImage1 =[[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-207, (SCREEN_HEIGHT/2-50) + 80 +20,414 , 63)];
    
    sketchMapImage1.image = [UIImage imageNamed:@"二维码引导1的副本"];
    
    UIImageView *sketchMapImage = [[UIImageView alloc] initWithFrame:CGRectMake(30,80, SCREEN_WIDTH-60, SCREEN_HEIGHT/2-50)];
    
    sketchMapImage.image = [UIImage imageNamed:@"二维码引导1——"];
    
    [self addMaskLayerRect:CGRectMake(SCREEN_WIDTH- pointFloat, pointFloat1, 40, 40) fingerPoint:CGPointMake(SCREEN_WIDTH - 70, 60) setTag:120 andImage:[UIImage imageNamed:@"image_1"] imageAry:@[[UIImage imageNamed:@"image_2"],[UIImage imageNamed:@"image_1"]] addSubview:@[sketchMapImage1,sketchMapImage]];
}

/**
 *  教程-设备列表引导
 */

-(void)AddDeviceListBoot
{
    
     
        ScrollView  = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT)];
        ScrollView.backgroundColor = [UIColor redColor];
        ScrollView.delegate = self;
        [ [ [ UIApplication  sharedApplication ]  keyWindow ] addSubview : ScrollView ] ;
        CGFloat Float;
        CGFloat Float1;
        if (SCREEN_WIDTH == 320) {
            Float= 80;
            Float1 = 180;
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
            
            Float= 120;
            Float1 = 320;
            
        }else{
            Float= 130;
            Float1=235;
        }
    
        for (int i =0; i<=2; i++)
        {
            //在这里给每一个ScrollView添加一个图片 和一个按钮
            UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
            [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"教程%d",i]]];
            UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(i*SCREEN_WIDTH+Float, SCREEN_HEIGHT/2-80, 150, 50);
            if (i==1) {
                button.frame = CGRectMake(i * SCREEN_WIDTH+Float, SCREEN_HEIGHT/2+50, 150, 50);
            }
            if (i==2) {
                button.frame = CGRectMake(i*SCREEN_WIDTH+Float, SCREEN_WIDTH/2+Float1, 150, 50);
            }
            
            button.tag =i;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            //把每页需要显示的VIEW添加进ScrollerView中
            [ScrollView addSubview:imageView];
            [ScrollView addSubview:button];
        }
        ScrollView.showsHorizontalScrollIndicator =NO;
        ScrollView.bounces = NO;
        ScrollView.pagingEnabled = YES;
        ScrollView.contentSize = CGSizeMake( self.view.bounds.size.width*3,self.view.bounds.size.height);
    
}




- (void)addMaskLayerRect:(CGRect)rect  fingerPoint:(CGPoint)point setTag:(NSInteger)tag andImage:(UIImage *)image imageAry:(NSArray <UIImage *> *)ary  addSubview:(NSArray <UIView *> *)views {
 // 为了不重复写这代码，就抽出来的 遮罩层
    if (self.holdedView == nil) {
        CGRect MDC_rect = rect;
        self.holdedView =[UtilToolsClss teturnMaskViewForObj:self maskLayerRect:MDC_rect fingerPoint:point setTag:tag layerRadius:30 andImage:image imageAry:ary];
        
        if (views != nil) {
            for(UIView *sonView in views) { [self.holdedView addSubview:sonView];}
        }
        [[UIApplication sharedApplication].keyWindow addSubview:self.holdedView];
        
    }
}

-(void)buttonClick:(UIButton *)button{

    if (button.tag==0) {
        
        [ScrollView setContentOffset:CGPointMake(self.view.bounds.size.width, 0) animated:YES];
        
    }else if (button.tag ==1){

        [ScrollView setContentOffset:CGPointMake(self.view.bounds.size.width*2, 0) animated:YES];

    }else if (button.tag == 2){
    
        [NSUD setObject:@"NO" forKey:@"QR"];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            ScrollView.alpha = 0;
        }completion:^(BOOL finished) {
            [ScrollView removeFromSuperview];
        }];
    }

    
    
}


-(void)didClickButton:(UIButton *)button{

    
    if (delete == NO) {
        EquipmenCell *cell = (EquipmenCell *)button.superview.superview;
        NSIndexPath *indexPath = [self.searchTableView indexPathForCell:cell];
        EListModel *listModel = _searchModelAry[indexPath.row];
        
        
        DetailspageViewController *D = [[DetailspageViewController alloc]init];
        
        D.imie = listModel.imie;
        [NSUD setObject:listModel.name forKey:@"device_name"];
        [self.navigationController pushViewController:D animated:YES];
        
    }
}


#pragma mark - Segues
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"jumpJournalList"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:recordChoiceDevice  forKey:@"journalDeviceCode"]; //设备编号
        [vc setValue:@(recordChoiceUnread) forKey:@"journalUnread"]; //未读条数
    }
}




/**
 *  天朝专用检测app更新
 */
-(void)hsUpdateApp
{
    //2先获取当前工程项目版本号
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    //3从网络获取appStore版本号
    NSError *error;
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=1213236353"]]] returningResponse:nil error:nil];
    if (response == nil) {
        NSLog(@"你没有连接网络哦");
        return;
    }
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"hsUpdateAppError:%@",error);
        return;
    }
    //    NSLog(@"%@",appInfoDic);
    NSArray *array = appInfoDic[@"results"];
    NSDictionary *dic = array[0];
    NSString *appStoreVersion = dic[@"version"];
    //打印版本号
    NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);
    //4当前版本号小于商店版本号,就更新
    if(![currentVersion isEqualToString: appStoreVersion])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",appStoreVersion] delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"更新",nil];
        [alert show];
    }else{
        NSLog(@"版本号好像比商店大噢!检测到不需要更新");
    }
    
}

- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //5实现跳转到应用商店进行更新
    if(buttonIndex==1)
    {
        //6此处加入应用在app store的地址，方便用户去更新，一种实现方式如下：
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/%E9%A3%8E%E7%94%B5%E6%97%81%E8%B7%AF%E8%BF%87%E6%BB%A4/id1213236353?l=zh&ls=1&mt=8"]];
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark -  getter
- (UIButton *)notDataBtn {
    if (!_notDataBtn) {
        _notDataBtn = [UtilToolsClss  noDataBtn:NSLocalizedString(@"No Results", @"没有设备")];
        
    }
    _notDataBtn.hidden = YES;
    return _notDataBtn;
}

- (NSString *)localStr {
    if (!_localStr) {
        _localStr = [NSString stringWithFormat:@"%d",[UtilToolsClss judgeLocalLanguage]];
    }
    return _localStr;
}


-(NSMutableArray *)searchModelAry
{
    if (!_searchModelAry) {
        _searchModelAry = [[NSMutableArray alloc]init];
    }
    return _searchModelAry;
}


@end
